package com.yuch.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuch.commons.R;
import com.yuch.entity.Book;
import com.yuch.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author YUCH
 */
@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public R<List<Book>> getAll() {
        List<Book> list = bookService.list();
        return R.success(list);

    }

    @PostMapping
    public R save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return flag ? R.success("保存成功") : R.error("保存失败");
    }

    @PutMapping
    public R<String> update(@RequestBody Book book) {
        boolean b = bookService.updateById(book);
        return b?R.success("修改成功"):R.error("修改失败");
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        boolean b = bookService.removeById(id);
        return b ? R.success("删除成功") : R.error("删除失败");
    }

        @GetMapping("{id}")
    public R<Book> getById(@PathVariable Integer id) {


            Book book = bookService.getById(id);
            return R.success(book);

    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize,Book book) {
        LambdaQueryWrapper<Book> query = new LambdaQueryWrapper<>();
        query.eq(!StringUtils.isEmpty(book.getName()),Book::getName,book.getName());
        query.eq(!StringUtils.isEmpty(book.getType()),Book::getType,book.getType());
        query.eq(!StringUtils.isEmpty(book.getDescription()),Book::getDescription,book.getDescription());
        Page<Book> objectPage = new Page<>(currentPage, pageSize);
        Page<Book> page = bookService.page(objectPage, query);
        if(currentPage>page.getPages()){
            page=bookService.page(new Page<>(page.getPages(),pageSize),query);
        }
        return R.success(page);
    }
}
